<template>
  <XenPageLayout
    title="招聘申请详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadRecruitRequestDetail(Id)"
  >
    <!-- 内容区域 -->
    <view
      class="details-container"
      :class="{ 'has-audit-actions': isMyApprove }"
    >
      <!-- 详情内容 -->
      <view class="details-card">
        <view class="card-content">
          <!-- 使用动态详情组件 -->
          <XenDynamicDetailsCard
            :sections="formSections"
            :data="originalData"
            :field-mapping="fieldMapping"
            :get-image-url="getImageUrl"
            @preview-image="previewImage"
          >
            <!-- 自定义明细列表插槽 -->
            <template #custom-sections>
              <XenDetailList
                title="招聘需求明细"
                :dataList="detailList"
                :loading="detailLoading"
                :displayFields="recruitRequestDetailFields"
                loadingText="加载中..."
                emptyText="暂无明细数据"
                keyField="ID"
              />
            </template>
          </XenDynamicDetailsCard>

          <!-- 审核时间线组件 - 所有用户都有权限查看 -->
          <XenAuditTimeline :steps="timelineData" />
        </view>
      </view>
    </view>

    <!-- 审核操作按钮组件 - 根据IsMyApprove字段控制显示 -->
    <XenAuditActions
      v-if="isMyApprove"
      ref="auditActionsRef"
      :actions="auditActions"
      @action="handleAuditAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicDetailsCard from "@/components/XenDynamicDetailsCard.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import XenAuditActions from "@/components/XenAuditActions.vue";
import XenDetailList from "@/components/XenDetailList.vue";
import {
  getFormSectionsByPageType,
  recruitRequestDetailFields,
} from "./form-config";
import { useRecruitRequestInfo } from "./composables/useInfo";

import commonApi from "@/api/common";
import SysHrRecruitRequestBillApi from "./api/index";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";
import type { ISysHrRecruitRequestBillVm } from "./api/interface";

// 获取详情页面的表单分组配置
const formSections = getFormSectionsByPageType("details");

// 页面状态
const Id = ref<string>("");
const hasError = ref<boolean>(false);

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);
const isMyApprove = ref<boolean>(false);
const auditLoading = ref<boolean>(false);
const auditActionsRef = ref();

// 创建API实例
const commonApiInstance = commonApi();
const api = SysHrRecruitRequestBillApi();

// 使用招聘需求申请信息 Composable
const {
  loading,
  originalData,
  getImageUrl,
  initializeOptions,
  loadRecruitRequestDetail,
  fieldMapping,
  detailList,
  detailLoading,
  loadDetailList,
} = useRecruitRequestInfo();

// 审核操作按钮配置
const auditActions = computed(() => [
  {
    key: "approve",
    label: "同意",
    type: "primary" as const,
    icon: "checkmarkempty",
    primary: true,
    customStyle: "background: #409eff; color: #ffffff;",
    disabled: auditLoading.value,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger" as const,
    icon: "closeempty",
    primary: true,
    customStyle: "background: #f56c6c; color: #ffffff;",
    disabled: auditLoading.value,
  },
]);

// 获取时间线数据
const getTimelineData = async () => {
  if (!Id.value) return;

  try {
    const params: QueryTimeline = {
      entityId: Id.value,
      entitytype: "HengTong.Model.Db.Bill.SysHrRecruitRequestBill",
    };

    const response = await commonApiInstance.getTimeline(params);
    timelineData.value = response || [];
  } catch (error) {
    console.error("获取时间线数据失败:", error);
    timelineData.value = [];
  }
};

// 处理审核操作
const handleAuditAction = (action: any, remark?: string) => {
  console.log("审核操作:", action, "审批原因:", remark);

  switch (action.key) {
    case "approve":
      handleApprove(remark);
      break;
    case "reject":
      handleReject(remark);
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 审核通过
const handleApprove = (remark?: string) => {
  // 直接执行同意操作，因为审批原因已经在组件中收集
  performAudit("同意", remark);
};

// 审核拒绝
const handleReject = (remark?: string) => {
  // 直接执行拒绝操作，因为拒绝原因已经在组件中收集
  performAudit("拒绝", remark);
};

// 执行审核操作
const performAudit = async (actionName: string, remark?: string) => {
  if (!originalData.value) {
    uni.showToast({
      title: "数据异常，请刷新页面重试",
      icon: "none",
    });
    return;
  }

  auditLoading.value = true;

  try {
    // 构造请求参数
    const requestData: ISysHrRecruitRequestBillVm = {
      ActionName: actionName,
      Entity: originalData.value,
      IsMyApprove: isMyApprove.value,
      Remark: remark || null, // 添加拒绝原因
    };

    // 调用审核接口
    const result = await api.approve(requestData);

    if (result) {
      // 关闭审批弹窗（同意和拒绝操作都需要关闭）
      if (actionName === "拒绝" || actionName === "同意") {
        auditActionsRef.value?.closeRejectPopup();
      }

      uni.showToast({
        title: `${actionName}成功`,
        icon: "success",
      });

      // 延迟1秒后刷新页面数据
      setTimeout(async () => {
        if (Id.value) {
          // 重新加载详情数据
          const loadResult = await loadRecruitRequestDetail(Id.value);
          if (loadResult.success) {
            // 重新设置审核权限标识
            isMyApprove.value = loadResult.isMyApprove || false;
            // 重新获取时间线数据
            await getTimelineData();
          }
        }
      }, 1000);
    }
  } catch (error) {
    console.error("审核操作失败:", error);

    // 处理不同类型的错误
    let errorMessage = "审核操作失败";
    if (error && typeof error === "object") {
      if ("message" in error && typeof error.message === "string") {
        errorMessage = error.message;
      } else if (
        "data" in error &&
        error.data &&
        typeof error.data === "object" &&
        "message" in error.data
      ) {
        errorMessage = error.data.message as string;
      }
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000,
    });
  } finally {
    auditLoading.value = false;
  }
};

// 预览图片 - 统一的图片预览函数
const previewImage = (fileId: string | null) => {
  if (!fileId) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  const imageUrl = getImageUrl(fileId);
  if (!imageUrl) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    fail: () => {
      uni.showToast({
        title: "预览图片失败",
        icon: "none",
      });
    },
  });
};

// 获取分享标题
const getShareTitle = () => {
  if (originalData.value?.BillCode) {
    return `招聘申请${originalData.value.BillCode}`;
  }
  return "招聘申请详情";
};

// 获取分享路径
const getSharePath = () => {
  if (Id.value) {
    return `/subpkg-hr-syshrrecruitrequestbill/details?id=${Id.value}`;
  }
  return "/subpkg-hr-syshrrecruitrequestbill/index";
};

// 页面加载时获取路由参数
onLoad((options) => {
  if (options?.id) {
    Id.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }

  // 设置微信小程序分享功能
  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    return {
      title: getShareTitle(),
      path: getSharePath(),
      imageUrl: "", // 可以设置分享图片
    };
  });
  // #endif
});

// 页面挂载后加载数据
onMounted(async () => {
  // 先加载选项数据
  await initializeOptions();

  if (Id.value) {
    const result = await loadRecruitRequestDetail(Id.value);
    if (!result.success) {
      hasError.value = true;
    } else {
      // 设置审核权限标识
      isMyApprove.value = result.isMyApprove || false;

      // 加载成功后，获取明细列表和时间线数据
      await Promise.all([loadDetailList(Id.value), getTimelineData()]);
    }
  }
});
</script>

<style lang="scss" scoped>
.details-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 80px);

  // 当有审核操作组件时，添加底部内边距避免遮挡
  &.has-audit-actions {
    padding-bottom: 100px; // 为审核操作组件预留空间
  }
  .details-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .card-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      .form-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .form-subtitle {
        font-size: 14px;
        color: #666;
      }
    }

    .card-content {
      padding: 24px;
    }
  }
}
</style>
